import http from '../../http'
export default {
    // 开启命名空间
    namespaced: true,
    state: {
        // 分类列表
        classifyList: [],
        // 购物车列表
        shopList: []
    },
    getters: {
        // 总数量
        allCount(state) {
            return state.shopList.reduce((prev, next) => {
                if (next.check) {
                    return prev + next.count
                } else {
                    return prev
                }
            }, 0)
        },
        // 总价格
        allPrice(state) {
            return state.shopList.reduce((prev, next) => {
                if (next.check) {
                    return prev + next.count * next.price
                } else {
                    return prev
                }
            }, 0)
        },
    },
    mutations: {
        // 添加商品
        addItem(state, action) {
            // 判断是否有商品
            // some 数组中有一个满足条件返回true
            let flag = state.shopList.some(item => item.id === action.id)
            if (flag) {
                action.count += 1
            } else {
                state.shopList.push(action)
            }
        },
        // 初始化赋值
        setClassify(state, action) {
            state.classifyList = action.list
        },
        // 添加购物车商品数量
        addCarItem(state, action) {
            state.shopList[action.index].count += 1
        },
        // 减少或删除商品
        remCarItem(state, { rem, index }) {
            // 如果该action.rem为true删除
            if (rem) {
                state.shopList.splice(index, 1)
            } else {
                state.shopList[index].count -= 1
            }
        },
        // 全选控制列表的check
        changeItemCheck(state, action) {
            state.shopList.forEach(item => item.check = action.check)
        }
    },
    // 处理异步任务
    actions: {
        init({ commit }) {
            http.get('/getList').then(res => {
                commit('setClassify', { list: res.data.data })
            })
        }
    }
}